#include "./BasicOpt.h"

Tree BuildTree(struct TreeNode T[]) {
    int num, Root;
    char cl, cr;
    printf("Set the number of tree node: ");
    scanf("%d\n", &num);
    int check[20] = {0};
    if (num) {
        // for (int i = 0; i < num; i++)
        // {
        //     check[i] = 0;
        // }

        for (int i = 0; i < num; i++)
        {
            scanf("%c,%c,%c\n", &T[i].element, &cl, &cr);
            if (cl != '-')
            {
                T[i].left = cl - '0';
                check[T[i].left] = 1;
            }
            else
            {
                T[i].left = Null;
            }
            if (cr != '-')
            {
                T[i].right = cr - '0';
                check[T[i].right] = 1;
            }
            else
            {
                T[i].right = Null;
            }
        }

        for (int i = 0; i < num; i++)
        {
            if (!check[i])
            {
                Root = i;
                break;
            }
        }
    }
    return Root;
}

int Isomorphic(Tree R1, Tree R2) {
    if((R1 == Null) && (R2 == Null)) {
        printf("Both trees are empty.");
        return 1;
    }

    if ((R1 == Null) || (R2 == Null))
    {
        char str[3];
        if (R1 == Null)
        {
            strcat(str, "R1");
        }
        else
        {
            strcat(str, "R2");
        }

        printf("Tree %s is empty.", str);
        return 0;
    }

    if (T1[R1].element != T2[R2].element)
    {
        printf("Roots are different. Trees are not isomorphic.");
        return 0;
    }

    if ((T1[R1].left == Null) && (T2[R2].left == Null))
    {
        return Isomorphic(T1[R1].right, T2[R2].right);
    }

    if (((T1[R1].left != Null) && (T2[R2].left != Null)) && ((T1[T1[R1].left].element) == (T2[T2[R2].left].element)))
    {
        return (Isomorphic(T1[R1].left, T2[R2].left) && Isomorphic(T1[R1].right, T2[R2].right));
    }

    else
    {
        return (Isomorphic(T1[R1].left, T2[R2].right) && Isomorphic(T1[R1].right, T2[R2].left));
    }

}
